import { requestInterceptor, responseInterceptor } from '../utils/request.js';

// API前缀
const API_PREFIX = 'http://127.0.0.1:8080';

/**
 * 创建API URL
 * @param {String} path - API路径
 * @returns {String} 完整的API URL
 */
const url = (path) => {
  return `${API_PREFIX}${path}`;
};

// 封装uni.request
const request = (options) => {
    // 确保URL有前缀
    if (options.url && !options.url.startsWith('http')) {
        options.url = url(options.url);
    }
    
    return new Promise(async (resolve, reject) => {
        try {
            // 请求拦截
            const interceptedRequest = await requestInterceptor(options);
            
            // 发起请求
            uni.request({
                ...interceptedRequest,
                success: async (res) => {
                    try {
                        // 保存原始请求配置
                        res.config = interceptedRequest;
                        
                        // 响应拦截
                        const interceptedResponse = await responseInterceptor(res);
                        resolve(interceptedResponse.data);
                    } catch (error) {
                        reject(error);
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        } catch (error) {
            reject(error);
        }
    });
};

/**
 * 所有API接口定义
 */
export default {
  // 用户相关
  user: {
    // 获取当前用户信息
    getCurrentUserInfo: () => {
        return request({
            url: `/system/user/profile`,
            method: 'GET'
        });
    },
    
    // 获取微信用户信息
    getWxUserInfo: (userId) => {
        return request({
            url: `/system/user/wx`,
            method: 'GET',
            data: { id: userId }
        });
    },
    
    // 获取用户资料
    userInfo: (userId) => {
        return request({
            url: `/system/user/${userId}`,
            method: 'GET'
        });
    },
    
    // 更新用户信息
    updateUserInfo: (data) => {
        return request({
            url: `/system/user/profile`,
            method: 'PUT',
            data: data,
            header: {
                'Content-Type': 'application/json'
            }
        });
    },
    
	// 获取作者
	publisherInfo: (publisherId) => {
        return request({
            url: `/appService/publishers/${publisherId}`,
            method: 'GET'
        });
    },
    
    // 获取推广信息
    getPromotionInfo: () => {
        return request({
            url: '/appService/promotion/info',
            method: 'GET'
        });
    },
    
    // 获取会员统计数据
    getMemberStats: () => {
        return request({
            url: '/appService/members/stats',
            method: 'GET'
        });
    },
    
    // 获取会员列表
    getMemberList: (params = {}) => {
        return request({
            url: '/appService/members/list',
            method: 'GET',
            data: params
        });
    },
    
    // 获取会员详情
    getMemberDetail: (params = {}) => {
        return request({
            url: '/appService/members/detail',
            method: 'GET',
            data: params
        });
    },
    
    // 解绑会员关系
    unbindMember: (params = {}) => {
        return request({
            url: '/appService/members/unbind',
            method: 'POST',
            data: params
        });
    }
  },
  
  // 通用接口
  common: {
    // 上传文件
    uploadFile: (filePath) => {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: url('/system/common/upload'),
          filePath: filePath,
          name: 'file',
          success: (uploadRes) => {
            try {
              const data = JSON.parse(uploadRes.data);
              resolve(data);
            } catch (e) {
              reject(new Error('上传文件解析响应失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    }
  },
  
  // 文章相关
  article: {
    // 获取文章列表
    getList: (params) => {
        return request({
            url: '/appService/products/list',
            method: 'GET',
            data: params
        });
    },
    
    // 获取文章详情
    getDetail: (id) => {
        return request({
            url: `/appService/products/${id}`,
            method: 'GET'
        });
    },
    
    // 添加文章
    add: (data) => request({
        url: '/content/article',
        method: 'POST',
        data: data
    }),
    
    // 更新文章
    update: (id, data) => request({
        url: `/content/article/${id}`,
        method: 'PUT',
        data: data
    }),
    
    // 删除文章
    delete: (id) => request({
        url: `/content/article/${id}`,
        method: 'DELETE'
    })
  },
  
  // 聊天相关
  chat: {
    // 获取聊天室列表
    getChatRooms: () => {
        return request({
            url: '/api/chat/rooms',
            method: 'GET'
        });
    },
    
    // 获取聊天消息
    getChatMessages: (roomId, page = 1, pageSize = 20) => {
        return request({
            url: '/api/chat/messages',
            method: 'GET',
            data: { roomId, page, pageSize }
        });
    },
    
    // 发送消息
    sendMessage: (data) => {
        return request({
            url: '/api/chat/messages',
            method: 'POST',
            data: data
        });
    },
    
    // 标记消息已读
    markMessagesAsRead: (roomId) => {
        return request({
            url: '/api/chat/messages/read',
            method: 'PUT',
            data: { roomId }
        });
    },
    
    // 创建私聊聊天室
    createPrivateChat: (expertId) => {
        return request({
            url: '/api/chat/private',
            method: 'POST',
            data: { expertId }
        });
    },
    
    // 加入群聊
    joinGroupChat: (groupId) => {
        return request({
            url: '/api/chat/group/join',
            method: 'POST',
            data: { groupId }
        });
    },
    
    // 退出群聊
    leaveGroupChat: (groupId) => {
        return request({
            url: '/api/chat/group/leave',
            method: 'POST',
            data: { groupId }
        });
    },
    
    // 检查专家聊天设置
    checkExpertChatSetting: (expertId) => {
        return request({
            url: '/api/chat/expert/setting',
            method: 'GET',
            data: { expertId }
        });
    }
  },
  
  // 订单相关
  order: {
    // 获取个人订单列表
    getMyOrders: (params = {}) => {
        return request({
            url: '/appService/orders/my',
            method: 'GET',
            data: params
        });
    },
    
    // 获取订单详情
    getOrderDetail: (orderId) => {
        return request({
            url: `/appService/orders/${orderId}`,
            method: 'GET'
        });
    },
    
    // 取消订单
    cancelOrder: (orderId) => {
        return request({
            url: `/appService/orders/${orderId}/cancel`,
            method: 'POST'
        });
    },
    
    // 支付订单
    payOrder: (orderId, paymentMethod) => {
        return request({
            url: `/appService/orders/${orderId}/pay`,
            method: 'POST',
            data: { paymentMethod }
        });
    },
    
    // 获取会员订单列表
    getMemberOrders: (params = {}) => {
        return request({
            url: '/appService/orders/member',
            method: 'GET',
            data: params
        });
    }
  },
  
  // 余额相关
  balance: {
    // 获取余额记录
    getBalanceLogs: (params = {}) => {
        return request({
            url: '/appService/balance/log/my',
            method: 'GET',
            data: params
        });
    }
  },
  
  // 可以方便地添加更多API模块...
  
  // 直接调用请求方法
  request: request
}; 